/*
 * 版权所有(c)  1952110078@qq.com  2022 - 2022
 */

package com.ldc.commonlibs.http.interceptor;

import androidx.annotation.NonNull;

import com.google.gson.JsonObject;
import com.ldc.commonlibs.conatants.NumberCode;
import com.ldc.commonlibs.conatants.ParamsConstants;
import com.ldc.commonlibs.utils.DataSourceUtil;
import com.ldc.commonlibs.utils.JsonUtil;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * @author liudc
 * @since 2022/7/10 23:49
 */
public class LoginInterceptor implements Interceptor {
    @NonNull
    @Override
    public Response intercept(@NonNull Chain chain) throws IOException {
        Request request = chain.request();
        return buildRequest(chain, request);
    }

    private Response buildRequest(Chain chain, Request request) throws IOException {
        Response response = chain.proceed(request);
        if (request.url().encodedPath().contentEquals("/login/cellphone")) {
            MediaType mediaType = response.body().contentType();
            String content = response.body().string();
            JsonObject data = JsonUtil.jsonToModel(content, JsonObject.class);
            getLoginData(data);
            ResponseBody responseBody = ResponseBody.create(content, mediaType);
            return response.newBuilder().body(responseBody)
                    .build();
        }
        return response;
    }

    private void getLoginData(JsonObject data) {
        if (data == null) {
            return;
        }
        int code = NumberCode.ERROR_CODE;
        if (data.has(ParamsConstants.code)) {
            code = data.get(ParamsConstants.code).getAsInt();
        }
        if (code == NumberCode.SUCCESS_CODE) {
            // 登录成功
            if (data.has(ParamsConstants.TOKEN)) {
                String str = data.get(ParamsConstants.TOKEN).getAsString();
                DataSourceUtil.putToken(str);
            }
            if (data.has(ParamsConstants.COOKIE)) {
                DataSourceUtil.putCookie(data.get(ParamsConstants.COOKIE).getAsString());
            }
            if (data.has(ParamsConstants.ACCOUNT)) {
                final String account = data.get(ParamsConstants.ACCOUNT).toString();
                DataSourceUtil.putAccountData(account);
            }
            if (data.has(ParamsConstants.PROFILE)) {
                final String profile = data.get(ParamsConstants.PROFILE).toString();
                DataSourceUtil.putProfileData(profile);
            }
            if (data.has(ParamsConstants.BINDINGS)) {
                final String bindings = data.get(ParamsConstants.BINDINGS).toString();
                DataSourceUtil.putBindingsData(bindings);
            }
        }
    }
}
